import React, { useState ,useEffect } from 'react';
import { Modal,Tree,message } from 'antd';
import { useIntl } from 'umi';
import type { TableListItem } from '../data.d';

export type FormValueType = {} & Partial<TableListItem>;
import { findRoleMenuList } from '../service';
import { getTreeList } from '../../menu/service';




const treeData = [
  {
    title: '0-0',
    key: '0-0',
    children: [
      {
        title: '0-0-0',
        key: '0-0-0',
        children: [
          { title: '0-0-0-0', key: '0-0-0-0' },
          { title: '0-0-0-1', key: '0-0-0-1' },
          { title: '0-0-0-2', key: '0-0-0-2' },
        ],
      },
      {
        title: '0-0-1',
        key: '0-0-1',
        children: [
          { title: '0-0-1-0', key: '0-0-1-0' },
          { title: '0-0-1-1', key: '0-0-1-1' },
          { title: '0-0-1-2', key: '0-0-1-2' },
        ],
      },
      {
        title: '0-0-2',
        key: '0-0-2',
      },
    ],
  },
  {
    title: '0-1',
    key: '0-1',
    children: [
      { title: '0-1-0-0', key: '0-1-0-0' },
      { title: '0-1-0-1', key: '0-1-0-1' },
      { title: '0-1-0-2', key: '0-1-0-2' },
    ],
  },
  {
    title: '0-2',
    key: '0-2',
  },
];

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  authModalVisible: boolean;
  values: Partial<TableListItem>;
};

const UpdateAuth: React.FC<UpdateFormProps> = (props) => {
  const fommat = (arrayList:any,pidStr = "parent_id",idStr = "id",childrenStr = "children") => {
    arrayList.push({
      title: "菜单信息",
      id: "1",
      parent_id: "0",
      menu_cascade: "menu_1_",
      level_num: "0",
      type: "0",
    });
    let listOjb = {}; // 用来储存{key: obj}格式的对象
    let treeList = []; // 用来储存最终树形结构数据的数组
    // 将数据变换成{key: obj}格式，方便下面处理数据
    for (let i = 0; i < arrayList.length; i++) {
      var data = arrayList[i];
      data.key = data.id;
      data.value = data.menu_cascade + ":" + data.level_num + ":" + data.type;
      if (data.child_num == 0) {
        data.isLeaf = true;
      }
      data.icon = "";
      listOjb[arrayList[i][idStr]] = data;
    }
    // 根据pid来将数据进行格式化
    for (let j = 0; j < arrayList.length; j++) {
      // 判断父级是否存在
      let haveParent = listOjb[arrayList[j][pidStr]];
      if (haveParent) {
        // 如果有没有父级children字段，就创建一个children字段
        !haveParent[childrenStr] && (haveParent[childrenStr] = []);
        // 在父级里插入子项
        haveParent[childrenStr].push(arrayList[j]);
      } else {
        // 如果没有父级直接插入到最外层
        treeList.push(arrayList[j]);
      }
    }
    return treeList;
  };
  
  const findMenuList = async () => {
    const hide = message.loading('正在查询');
    try {
      await getTreeList({}).then(res =>{
        const treeData = fommat(
          res.data,
          "parent_id"
        );
        // treeData = treeData;
        setTreeData(treeData);
      })
      hide();
      // message.success('数据查询成功');
      return true;
    } catch (error) {
      hide();
      // message.error('数据查询失败');
      return false;
    }
  };
  
  const findRMList = async (roleId:string) => {
    const hide = message.loading('正在查询');
    try {
      await findRoleMenuList({ role_id: roleId }).then(res =>{
        let ids = res.data.map((menu_id:string) => {
          return menu_id;
        });
        setCheckedKeys(ids);
      })
      hide();
      // message.success('数据查询成功');
      return true;
    } catch (error) {
      hide();
      // message.error('数据查询失败');
      return false;
    }
  };

  useEffect(() => {
    findMenuList();
    findRMList(props.values.id+"");

  }, [props.authModalVisible]);


  const intl = useIntl();
  let index = 0;
  const handleOk = () => {
    let values = {};
    values = {ids:checkedKeys.join(",")}
    props.onSubmit(values);
    if(index>0){
      props.onCancel()
    }
    index++;
  };
  const handleCancel = () => {
    props.onCancel()
  }
 

  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(['1']);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [treeData, setTreeData] = useState<any>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);

  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: React.Key[]) => {
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    setSelectedKeys(selectedKeysValue);
  };

  // setInitValues(props.values);
  return (
    <Modal
      width={320}
      title={intl.formatMessage({
        id: '权限分配',
        defaultMessage: '权限分配',
      })}
      visible={props.authModalVisible}
      destroyOnClose
      onOk={handleOk} onCancel={handleCancel}
      // onFinish={props.onSubmit}
      // onVisibleChange={handleOk}
      // initialValues={props.values}
    >
      <Tree
      checkable
      onExpand={onExpand}
      expandedKeys={expandedKeys}
      autoExpandParent={autoExpandParent}
      onCheck={onCheck}
      checkedKeys={checkedKeys}
      onSelect={onSelect}
      selectedKeys={selectedKeys}
      treeData={treeData}
    />
    </Modal>    
  );
};

export default UpdateAuth;
